package com.lz.helper.idcard

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.lz.helper.HelperConfig
import java.lang.ref.WeakReference

//身份证识别
class IDCardHelper(
    context: Context,
    readFinger: Boolean,
    callback: IDCardCallback,
    factory: IDCardRequest.Factory = DefFactory()
) :
    Handler(Looper.getMainLooper()), IDCardRequest.IDCardHandler {

    companion object {
        private const val MSG_RESULT = 1
        private const val MSG_ERR = 2
    }

    override fun handleMessage(msg: Message) {
        when (msg.what) {
            MSG_RESULT -> reference.get()?.onCardResult(msg.obj as IDCardInfo)
            MSG_ERR -> reference.get()?.onCardError(msg.obj as Int)
        }
    }

    //核心处理
    private val request by lazy { factory.create(context.applicationContext, readFinger, this) }

    //回调
    private val reference = WeakReference(callback)

    //线程是否开启
    private var hasStarted = false

    fun start() {
        if (!hasStarted) {
            hasStarted = true
            Thread(request, "IDCardRequest-Thread").start()
        }
    }

    fun restart() {
        if (hasStarted) request.restart()
    }

    fun pause() {
        request.pause()
    }

    fun quit() {
        request.quit()
    }

    override fun sendCardResult(idCard: IDCardInfo) {
        sendMessage(obtainMessage(MSG_RESULT, idCard))
    }

    override fun sendCardError(code: Int) {
        sendMessage(obtainMessage(MSG_ERR, code))
    }

    interface IDCardCallback {

        //识别成功
        fun onCardResult(idCardInfo: IDCardInfo)

        //失败系列
        fun onCardError(err: Int)
    }

    class DefFactory : IDCardRequest.Factory {

        override fun create(
            context: Context,
            readFinger: Boolean,
            handler: IDCardRequest.IDCardHandler
        ): IDCardRequest {
            return when (HelperConfig.flatNum()) {
                16 -> SerialIDCardRequest(context, readFinger, handler) //辽源通达串口
                else -> UIDCardRequest(context, readFinger, handler) //辽源通达U口或者老像素, 新像素
            }
        }
    }
}